package cn.unknowpupil.init.controller.system;

import cn.unknowpupil.init.async.AsyncFactory;
import cn.unknowpupil.init.async.AsyncManager;
import cn.unknowpupil.init.common.constant.CacheKeyConstants;
import cn.unknowpupil.init.common.enums.BusinessType;
import cn.unknowpupil.init.common.resopnse.ResultResponse;
import cn.unknowpupil.init.components.annotation.Log;
import cn.unknowpupil.init.components.annotation.RepeatSubmit;
import cn.unknowpupil.init.domain.dto.LoginUser;
import cn.unknowpupil.init.domain.system.SysPermission;
import cn.unknowpupil.init.service.system.ISysPermissionService;
import cn.unknowpupil.init.utils.redis.RedisUtils;
import cn.unknowpupil.init.utils.security.SecurityUtils;
import cn.unknowpupil.init.utils.strings.StringUtils;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * Created at 2020/11/25 by w10g <br>
 * Initialize SysPermissionController ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Api(tags = {"系统-权限表模块"}, value = "SysPermission")
@RestController
@RequestMapping(value = "admin/sys-permission")
public class SysPermissionController {
    @Autowired
   private ISysPermissionService permissionService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private AsyncManager asyncManager;
    /**
     * 新增
     *
     * @param permission {@link SysPermission}  权限表
     * @return {@link ResultResponse}
     */
    @ApiOperation("系统：新增权限")
    @Log(title = "新增权限", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PreAuthorize("@ps.hasPerm('system:permission:create')")
    @PostMapping("create")
    public ResultResponse create(@Validated @RequestBody SysPermission permission) {
        redisUtils.del(CacheKeyConstants.PERMISSION_LIST);
        // 业务逻辑
        boolean created = permissionService.create(permission);
        asyncManager.execute(AsyncFactory.reSavePermissionList());
        if (created) {
            return ResultResponse.success("创建成功");
        }else{
            return ResultResponse.buildFailure("创建失败");
        }

    }

    /**
     * 修改
     *
     * @param permission {@link SysPermission}  权限表
     * @return {@link ResultResponse}
     */
    @ApiOperation("系统：修改权限")
    @Log(title = "修改权限", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PreAuthorize("@ps.hasPerm('system:permission:update')")
    @PutMapping("update")
    public ResultResponse update(@Validated @RequestBody SysPermission permission) {
        redisUtils.del(CacheKeyConstants.PERMISSION_LIST);
        // 业务逻辑
        boolean update = permissionService.update(permission);
        asyncManager.execute(AsyncFactory.reSavePermissionList());
        if (update) {
            return ResultResponse.success("修改成功");
        }else{
            return ResultResponse.buildFailure("修改失败");
        }

    }
    /**
     * 获取
     *
     * @param permissionId {@code Long}
     * @return {@link ResultResponse}
     */
    @ApiOperation("系统：获取权限")
    @GetMapping("get/{permissionId}")
    public ResultResponse get(@PathVariable("permissionId") Long permissionId) {
        SysPermission permission = permissionService.info(permissionId);
        return ResultResponse.buildSuccess(permission);
    }


    /**
     * 删除
     *
     * @param permissionId {@code Long}
     * @return {@link ResultResponse}
     */
    @ApiOperation("系统：删除权限")
    @Log(title = "删除权限", businessType = BusinessType.DELETE)
    @PreAuthorize("@ps.hasPerm('system:permission:delete')")
    @RepeatSubmit
    @DeleteMapping("remove/{permissionId}")
    public ResultResponse remove(@PathVariable("permissionId") Long permissionId) {

        // 业务逻辑
        boolean deleted  = permissionService.delete(permissionId);
        asyncManager.execute(AsyncFactory.reSavePermissionList());
        if(deleted){
            return ResultResponse.success("删除成功");
        }else{
            return ResultResponse.buildFailure("删除失败");
        }
    }
    /**
     * 查询所有权限
     * @return
     */
    @ApiOperation(value = "所有权限" ,  notes="查询所有权限")
    @RequestMapping(value="/list",method = {RequestMethod.POST, RequestMethod.GET})
    public ResultResponse list(){

        Object permission = redisUtils.get(CacheKeyConstants.PERMISSION_LIST);
        if(StringUtils.isNull(permission)){
            List<SysPermission> trees = permissionService.getPermissionList();
            boolean set = redisUtils.set(CacheKeyConstants.PERMISSION_LIST, trees);
            return ResultResponse.buildSuccess(trees);
        }else {
            List<SysPermission> sysPermissions = StringUtils.cast(permission);
            return ResultResponse.buildSuccess(sysPermissions);
        }


    }
    /**
     * 获取权限下拉树列表
     */

    @ApiOperation("系统：获取权限下拉树列表")
    @GetMapping("/tree")
    public ResultResponse tree(SysPermission permission) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysPermission> permissions = permissionService.selectPermissionList(permission, loginUser);
        return ResultResponse.buildSuccess(permissionService.buildPermissionTreeSelect(permissions));
    }


    /**
     * 加载对应角色权限列表树
     */
    @ApiOperation("系统：加载对应角色权限列表树")
    @GetMapping("/rolePermissionTree/{roleId}")
    public ResultResponse roleMenuTree(@PathVariable("roleId") Long roleId)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysPermission> permissions = permissionService.selectPermissionList(loginUser);
        Map<String,Object> result = Maps.newHashMap();
        // 检查关键词
        result.put("checkedKeys", permissionService.selectPermissionListByRoleId(roleId));
        result.put("permission", permissionService.buildPermissionTreeSelect(permissions));

        return ResultResponse.buildSuccess(result);
    }
}
